package frog.lazy.framework.datasource.aspect;

import frog.lazy.framework.datasource.DynamicDataSourceContextHolder;
import frog.lazy.framework.datasource.annotation.TargetDataSource;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import java.util.Random;

@Aspect
@Order(-1)//保证在@Transactional之前执行
@Configuration
public class DynamicDataSourceAspect {

    /**
     *
     * @param joinPoint
     * @param targetDataSource
     */
    @Before("@annotation(targetDataSource)")
    public void changeDataSource(JoinPoint joinPoint, TargetDataSource targetDataSource) {
        String dbid = targetDataSource.name();
        if(dbid.equals("auto")){
            // 表示随机分配
            Random r = new Random();
            int datasource = r.nextInt(DynamicDataSourceContextHolder.dataSourceIds.size() - 1);
            int index = datasource%(DynamicDataSourceContextHolder.dataSourceIds.size() - 1);
            index = index + 1;
            DynamicDataSourceContextHolder.setDataSourceType(DynamicDataSourceContextHolder.dataSourceIds.get(index));

        }else{
            if (!DynamicDataSourceContextHolder.isContainsDataSource(dbid)) {
            } else {
                DynamicDataSourceContextHolder.setDataSourceType(dbid);
            }
        }
    }

    @After("@annotation(targetDataSource)")
    public void clearDataSource(JoinPoint joinPoint, TargetDataSource targetDataSource) {
        DynamicDataSourceContextHolder.clearDataSourceType();
    }
}
